const fs = require("fs");
const path = require("path");

const db = require("../config/dbserver.js");

// 取出 这个json 文件 ip
function getIpJson() {
  const pathV = path.resolve(__dirname, "../public/json/ip.json");
  const ipJson = fs.readFileSync(pathV, "utf8");
  return JSON.parse(ipJson);
}

// 存入 ip
function setIpJson(ipJson) {
  const pathV = path.resolve(__dirname, "../public/json/ip.json");
  fs.writeFileSync(pathV, JSON.stringify(ipJson));
}

// 写入数据库
async function setIpJsonDb(ip, data = "") {
  // console.log("set ip", ip);
  const sql = `
  INSERT INTO ips (ip,data,created_at) VALUES (?,?,TIME_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s'))
  `;
  const params = [ip, data];
  const connect = await db.dbConnect();
  return connect.execute(sql, params);
}

module.exports = {
  getIpJson,
  setIpJsonDb
};
